package org.familysearch.fsapi.gwt.server.dao.rest.parsers;

import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.familysearch.fsapi.gwt.common.client.entities.Temple;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TempleSAXParser extends DefaultHandler {

	private String tempVal = "";
	private Temple t = null;
	private ArrayList<Temple> temples = new ArrayList<Temple>();
	private boolean isTemple = false;
	private Logger log;
	
	public TempleSAXParser()
	{	
		log = Logger.getLogger(this.getClass().getName());
	}
	
	public void startElement(
			String uri, 
			String localName, 
			String qName,
			Attributes attributes) throws SAXException {

			// parse temple
			if(qName.equalsIgnoreCase("temple")) {
				
				/*
				 * There are two <temple> tags.
				 * The first one is has an attribute called statusCode
				 */
				if( attributes.getValue("statusCode") != null )
				{
					isTemple = false;
				}
				
				/*
				 * The temple object we want has a 'code' attribute
				 */
				if( attributes.getValue("code") != null)
				{
					t = new Temple();
					t.setCode(attributes.getValue("code"));
					isTemple = true;
				}
			}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		tempVal = new String(ch,start,length);
	}

	public void endElement(String uri, String localName,
			String qName) throws SAXException {

			if(qName.equalsIgnoreCase("temple")) {
				//add it to the list
				if( isTemple )
				{
					temples.add(t);
					isTemple = false;
				}

			}else if (qName.equalsIgnoreCase("name")) {
				t.setName(tempVal);
			}else if (qName.equalsIgnoreCase("location")) {
				t.setName(tempVal);							
			}
			
			// at the end of every element, turn off isTemple
			//isTemple = false;
						
			
	}

	public ArrayList<Temple> getTemples() {
		/*
		 * Workaround for extra <temple> node parsing
		 * - pop off last item
		 */
		//temples.remove(temples.size()-1);
		return temples;
	}

	public void setTemples(ArrayList<Temple> temples) {
		this.temples = temples;
	}
	

}
